package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"strconv"

	"github.com/gin-gonic/gin"
)

type ConfigService struct {
	repo repository.ConfigRepository
}

func NewConfigService(repo repository.ConfigRepository) *ConfigService {
	return &ConfigService{repo: repo}
}

func (s *ConfigService) CreateConfig(c *gin.Context) {
	var config model.Config
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.Create(&config); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, config)
}

func (s *ConfigService) GetConfigByID(c *gin.Context) {
	id := c.Param("id")

	// 将 id 字符串转换为 uint 类型
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	config, err := s.repo.GetByID(uint(idUint))
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, config)
}

func (s *ConfigService) GetConfigByCode(c *gin.Context) {
	code := c.Param("code")
	config, err := s.repo.GetByCode(code)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, config)
}

func (s *ConfigService) UpdateConfig(c *gin.Context) {
	var config model.Config
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.Update(&config); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, config)
}

func (s *ConfigService) DeleteConfig(c *gin.Context) {
	id := c.Param("id")
	// 将 id 字符串转换为 uint 类型
	idUint, errConv := strconv.ParseUint(id, 10, 64)
	if errConv != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	if err := s.repo.Delete(uint(idUint)); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}

func (s *ConfigService) ListConfigsByGroup(c *gin.Context) {
	groupCode := c.Param("groupCode")
	configs, err := s.repo.ListByGroup(groupCode)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, configs)
}
